package work.chenbo.mybatis.customize.session.impl;

import work.chenbo.mybatis.customize.config.Configuration;
import work.chenbo.mybatis.customize.config.MappedStatement;
import work.chenbo.mybatis.customize.session.Executor;
import work.chenbo.mybatis.customize.session.SqlSession;

import java.util.List;

/**
 * @author ChenBo
 * @className DefaultSqlSession
 * @date 2020/12/23
 */
public class DefaultSqlSession implements SqlSession {

    private Configuration configuration;

    private Executor executor;

    public DefaultSqlSession(Configuration configuration){
        this.configuration = configuration;
        this.executor = new SimpleExecutor();
    }

    @Override
    public <E> List<E> selectList(String statementId, Object... params) throws Exception {
        MappedStatement mappedStatement = configuration.getMappedStatementMap().get(statementId);
        List<Object> query = executor.query(configuration, mappedStatement, params);
        return (List<E>) query;
    }

    @Override
    public <T> T selectOne(String statementId, Object... params) throws Exception {
        MappedStatement mappedStatement = configuration.getMappedStatementMap().get(statementId);
        List<Object> query = executor.query(configuration, mappedStatement, params);
        if(query!=null && query.size() == 1){
            return (T) query.get(0);
        }
        return null;
    }
}
